package com.example.demo.Task;

import com.example.demo.domain.dto.ClassInfo;
import com.example.demo.domain.send.DingMessage;
import com.example.demo.service.ScheduleService;
import com.example.demo.service.SendDingMessageService;
import com.example.demo.utils.ParseUtil;
import java.util.Arrays;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * 定时任务爬取课表信息
 *
 * @author lizijian
 */
@Slf4j
@Component
public class GetScheduleTask implements Runnable {

  private static final ThreadPoolTaskExecutor GET_SCHEDULE_POOL = new ThreadPoolTaskExecutor();

  static {
    GET_SCHEDULE_POOL.setRejectedExecutionHandler(new CallerRunsPolicy());
    GET_SCHEDULE_POOL.setCorePoolSize(10);
    GET_SCHEDULE_POOL.setMaxPoolSize(10);
    GET_SCHEDULE_POOL.setQueueCapacity(1500);
    GET_SCHEDULE_POOL.setWaitForTasksToCompleteOnShutdown(true);
    GET_SCHEDULE_POOL.initialize();
  }


  private ScheduleService scheduleService;

  @Autowired
  public GetScheduleTask(ScheduleService scheduleService) {
    this.scheduleService = scheduleService;
  }


  @Override
  public void run() {
    List<ClassInfo> classNameList = null;
    try {
      log.info("开始爬取所有班级课表");
      SendDingMessageService.sendGetDataMessage(new DingMessage("开始爬取所有班级课表"));
      classNameList = ParseUtil.getAllClass();
      log.info("班级总数:" + classNameList.size());
      scheduleService.deleteSchedule();
      for (ClassInfo classInfo : classNameList) {
        GetClassScheduleThread getClassScheduleThread = new GetClassScheduleThread(
            scheduleService, classInfo);
        GET_SCHEDULE_POOL.execute(getClassScheduleThread);
      }
      log.info("所有班级爬取线程已开启");
    } catch (Exception e) {
      log.error("getAllClass error");
      log.error("stack:" + Arrays.toString(e.getStackTrace()));
      SendDingMessageService.sendGetDataMessage(new DingMessage("爬取所有班级课表失败,errorMessage:"+e.getMessage()));
    }
  }
}
